package com.juzipi.common.utils.security;


import com.juzipi.common.model.LoginBody;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * Security工具类
 */

public class SecurityUtils {


    /**
     * 获取用户名
     * @return String
     */
    public static String getUsername(){
        return getLoginUser().getUsername();
    }


    /**
     * 获取用户
     * @return loginBody
     */
    public static LoginBody getLoginUser(){
        return (LoginBody) getAuthentication().getPrincipal();
    }


    /**
     * 获取Authentication
     * @return Authentication
     */
    public static Authentication getAuthentication(){
        return SecurityContextHolder.getContext().getAuthentication();
    }


    /**
     * 生成BCryptPasswordEncoder加密的密码
     * @param password 要加密的数据
     * @return 加密后的结果
     */
    public static String encryptPassword(String password){
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }


    /**
     * 判断密码是否相同
     * @param rawPassword 原密码
     * @param encodePassword 加密后的
     * @return true 相同，false 不同
     */
    public static boolean matchesPassword(String rawPassword,String encodePassword){
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder.matches(rawPassword, encodePassword);
    }


}
